package api

import (
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego/validation"
	"github.com/gin-gonic/gin"
	"go_api/models/ucenter"
	"go_api/pkg/util"
	"go_api/pkg/weapp"
	"go_api/service/user_service"
	"go_api/service/wechat_service"
	"net/http"
	"strconv"
	"strings"

	"go_api/pkg/app"
	"go_api/pkg/e"
	"go_api/service/auth_service"
)

type param struct {
	Username 			string  `valid:"Required"`
	Password 			string  `valid:"Required"`
	Code 	 			string  `valid:"Required"`
	Nickname			string	`valid:"Required"`
	AvatarUrl			string	`valid:"Required"`
}

func Login(c *gin.Context) {
	appG := app.Gin{C: c}
	valid := validation.Validation{}

	username := c.PostForm("username")
	password := c.PostForm("password")
	code	 := c.PostForm("code")
	nickname := c.PostForm("nickname")
	avatarUrl := c.PostForm("avatarUrl")
	a := param{Username: username, Password: password, Code: code, Nickname:nickname, AvatarUrl:avatarUrl}
	ok, _ := valid.Valid(&a)

	if !ok {
		app.MarkErrors(valid.Errors)
		appG.ErrorResponse(http.StatusBadRequest, e.GetMsg(e.INVALID_PARAMS))
		return
	}

	authService := auth_service.Auth{Username: username,}
	//ucenter 开始验证
	err, member := authService.GetOneMember()
	if err != nil {
		appG.ErrorResponse(http.StatusInternalServerError, e.GetMsg(e.ERROR))
		return
	}

	if !(member.UID > 0) {
		appG.ErrorResponse(http.StatusNotFound, "用户不存在")
		return
	}
	//检测uid 在study 是否存在
	userService := user_service.User{UID: member.UID}
	err, user := userService.CheckUserUID()
	if err != nil {
		appG.ErrorResponse(http.StatusInternalServerError, e.GetMsg(e.ERROR))
		return
	}

	if !(user.ID > 0) {
		appG.ErrorResponse(http.StatusNotFound, "请先注册study")
		return
	}

	if util.EncodeMD5(util.EncodeMD5(password) + member.Salt) == member.Password {
		token, err := util.GenerateToken(username, password,member.Role, member.UID, user.ID)
		if err != nil {
			appG.ErrorResponse(http.StatusInternalServerError, e.GetMsg(e.ERROR_AUTH_TOKEN))
			return
		}
		//获取weapp 的open_id
		isSuccess, str := weapp.GetWeAppOpenId(code)
		if !isSuccess {
			appG.ErrorResponse(http.StatusBadRequest, str)
			return
		}

		//根据open_id 查找 wechat 记录
		chatService := wechat_service.WeChat{WeappOpenId: str, UID: member.UID}
		err, chat := chatService.ExistByOpenIdWeChat()
		if err != nil {
			appG.ErrorResponse(http.StatusInternalServerError, e.GetMsg(e.ERROR))
			return
		}
		if chat.ID > 0 {
			err := chatService.UpdateWeChatDeleteAt()
			if err != nil {
				appG.ErrorResponse(http.StatusBadRequest, "请重新授权")
				return
			}
		} else {
			var meta ucenter.Meta
			if err := json.Unmarshal([]byte(member.Meta), &meta); err == nil {
				fmt.Println("================json str 转struct==")
				fmt.Println(meta)
				fmt.Println(meta.City)
			}
			chatService.Nickname = nickname
			chatService.School = meta.City
			chatService.Avatar = avatarUrl
			addErr := chatService.AddWeChat()
			if addErr != nil {
				appG.ErrorResponse(http.StatusBadRequest, "创建记录失败，请重试！")
				return
			}
		}

		//推送绑定成功模版消息
		//todo
		appG.Response(http.StatusOK, gin.H{
			"access_token": token,
			"username": member.Username,
			"uid": member.UID,
			"openid": str,
			"role": strings.ToLower(member.Role),
			"nickName": nickname,
			"avatarUrl": avatarUrl,
		})

		return
	}
	appG.ErrorResponse(http.StatusBadRequest, "密码错误")
	return
}

type logoutParam struct {
	OpenId 		string 	`valid:"Required; MaxSize(50)"`
	UID 		string 	`valid:"Required"`
}

func Logout(c *gin.Context) {
	appG := app.Gin{C: c}
	valid := validation.Validation{}
	open_id := c.PostForm("openid")
	uid		:= c.PostForm("uid")
	a := logoutParam{OpenId: open_id, UID: uid}
	ok, _ := valid.Valid(&a)
	if !ok {
		app.MarkErrors(valid.Errors)
		appG.ErrorResponse(http.StatusBadRequest, e.GetMsg(e.INVALID_PARAMS))
		return
	}
	newUid, _ := strconv.Atoi(uid)
	chatService := wechat_service.WeChat{WeappOpenId: open_id, UID: newUid}
	err := chatService.DeleteWeChat()
	if err != nil {
		appG.ErrorResponse(http.StatusInternalServerError, e.GetMsg(e.ERROR))
		return
	}
	appG.Response(http.StatusOK, "解绑成功!")

	return

}
